package ar.edu.itba.pod.legajo45129.statistics;

import java.rmi.RemoteException;

import org.apache.log4j.Logger;

import ar.edu.itba.pod.legajo45129.Configuration;
import ar.edu.itba.pod.legajo45129.simul.communication.ConnectionManagerImpl;
import ar.edu.itba.pod.legajo45129.simul.communication.factory.MessageFactory;
import ar.edu.itba.pod.simul.communication.Message;

public class GetStatistics implements Runnable {

	private static Logger logger = Logger.getLogger(GetStatistics.class);
	private long statisticsWaitTime;
	private ConnectionManagerImpl connectionManager;
	
	public GetStatistics(ConnectionManagerImpl connectionManager) {
		this.connectionManager = connectionManager;		
		statisticsWaitTime = Configuration.StatisticsWaitTime;
	}
	
	@Override
	public void run() {
		String localnode = connectionManager.getNodeId().toString();
		Message message = MessageFactory.NodeMarketDataRequest(localnode);
		
		logger.debug("broadcast a NODE_MARKET_DATA_REQUEST message");
		try {
			connectionManager.getGroupCommunication().broadcast(message);
		} catch (RemoteException e) {
			logger.error("error while broadcasting message: " +  e);
			return;
		}
		
		try {
			Thread.sleep(statisticsWaitTime);
		} catch (InterruptedException e) {
			logger.fatal("There was an error while waiting for the messages to arrive", e);
		}
		
		Statistics.getInstance().printOnScreen();
	}
}
